package com.wxq.auth.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.wxq.auth.config.JwtProperties;
import com.wxq.auth.exception.AuthBizException;
import com.wxq.auth.feign.MemberFeignService;
import com.wxq.auth.vo.UserLoginVO;
import com.wxq.auth.vo.UserRegisterVO;
import com.wxq.common.constant.AuthConstant;
import com.wxq.common.utils.R;
import com.wxq.auth.service.SmsService;
import com.wxq.common.vo.MemberVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Jim
 * @date 6:40 下午 2022/4/10
 * @description 发送短信验证码
 * @email:huwmz04153277@126.com
 */
@EnableConfigurationProperties(JwtProperties.class)
@Controller
public class LoginController {
    @Autowired
    SmsService smsService;

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 发送短信
     * @param mobile
     * @return
     */
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("mobile") String mobile){
        try {
        smsService.sendCode(mobile);
    } catch (AuthBizException e) {
        return R.error(e.getCode(), e.getMessage());
    }
        return R.ok();
    }

    @ResponseBody
    @GetMapping("/check/user/{username}")
    public R checkUser(@PathVariable("username") String username){
        R r = memberFeignService.checkUser(username);
        return r;
    }

    /**
     * 检查手机是否存在
     * @param mobile
     * @return
     */
    @ResponseBody
    @GetMapping("/check/mobile/{mobile}")
    public R checkMobile(@PathVariable("mobile") String mobile){
        R r = memberFeignService.checkMobile(mobile);
        return r;
    }

    /**
     *
     * @param registerVO
     * @param result
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/reg")
    public String register(@Valid UserRegisterVO registerVO, BindingResult result,
                           RedirectAttributes redirectAttributes){
        if (result.hasErrors()) {
            //收集错误消息
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(
                    FieldError::getField,FieldError::getDefaultMessage
            ));
            redirectAttributes.addFlashAttribute("errors",errors);
            //校验出错，重定向到注册页面
            //重定向携带数据，利用Session，到目标页面从Session中取出数据，然后剔除session中的数据
            //分布式sessio问题
            return "redirect:http://auth.yomall.com/reg.html";
        }
        //校验验证码，考虑验证码是佛国旗
        boolean b = smsService.checkCode(registerVO.getMobile(),registerVO.getCode());
        if (!b){
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.yomall.com/reg.html";
        }
        //调用远程会员注册
        R r = memberFeignService.register(registerVO);
        if (r.getCode() != 0){
            Map<String, String> errors = new HashMap<>();
            errors.put("msg",r.getData("msg", new TypeReference<String>() {}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.yomall.com/reg.html";
        }
        //注册成功，重定向到登录页
        return "redirect:http://auth.yomall.com/login.html";
    }

    /**
     * 登陆
     * @param vo
     * @param redirectAttributes
     * @param session
     * @return
     */
    @PostMapping("login")
    public String login(UserLoginVO vo, RedirectAttributes redirectAttributes, HttpSession session){
        //调用远程接口
        R  r = memberFeignService.login(vo);
        if (r.getCode() != 0){
            Map<String, String> errors = new HashMap<>();
            String msg = r.getData("msg", new TypeReference<String>() {});
            errors.put("msg",msg);
            redirectAttributes.addFlashAttribute("errors",errors);
            //登陆失败，重定向到登录页
            return "redirect:http://auth.yomall.com/login.html";
        }
        //将用户信息放入到session中
        MemberVO memberVO = r.getData("data", new TypeReference<MemberVO>() {});
        session.setAttribute(AuthConstant.SESSION_LOGIN_USER,memberVO);
        //登陆成功
        return "redirect:http:yomall.com";
    }

    /**
     * @param session
     * @return
     */
    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthConstant.SESSION_LOGIN_USER);
        if (attribute != null){
            //用户登录，跳转到首页
            return "redirect:http:yomall.com";
        }
        return "login";
    }
}
